// launch this via "node launcher.js".
// to select a game, visit the hosting computer's IP address in a web browser.
// example: http://192.168.1.50:1337/?game=dkong
// This should launch Donkey Kong on the computer running the app.

// You'll need to configure the following 3 lines to match your environment:
var mameDirectory = "c:/mamesrc/";
var mameExe = "mame64.exe";
var mameOptions = ""; // like '-window' or maybe '-video ddraw' or whatever.

var port = 1337;

var kill = 'taskkill.exe /pid';
var psgrep = 'tasklist /fo csv | findstr';

// no configuration below this line //
require('shelljs/global');  // "npm install shelljs" - this is where synchronous exec() comes from.

var http = require('http');
var url = require('url');

var execa = require('child_process').exec;  // rename exec() to execa() to make room for synchronous exec.

var child;
var childpid;

http.createServer(function (req, res) {
	var queryData = url.parse(req.url, true).query;

	res.writeHead(200, {'Content-Type': 'text/html'});
	
	function launch(game) {
		game = game.replace(/;.*$/, ''); // strip out sneaky shit on unix & mac.
		game = game.replace(/&.*$/, ''); // strip out sneaky shit on windows.
		
		child = execa(mameExe + ' ' + mameOptions + ' ' + game, { cwd: mameDirectory }, function(error, stdout, stderr) {
			if (error) { res.write(stderr); }
			if (stdout) { console.log(stdout); }
			if (stderr) { console.log(stderr); }
		});
		
		child.on('exit', function(code) {
			child = null;
		});
	}
	
	if (queryData.game) {
	    // you'll need to modify this for Linux & Unix.
		childpid = exec(psgrep + ' ' + mameExe, {silent:true}).output.split(',')[1];
		
		if (childpid) {
			// you'll need to modify this for unix. //
			childpid = childpid.replace(/"/g, '');
			console.log('killing mame.');
			exec(kill + ' ' + childpid, {silent:true});
		}
		
		res.write('hello ' + queryData.game + '.\n');
				
		if (queryData.game != 'exit') {
		    launch(queryData.game);
		    console.log('launching ' + queryData.game);
		} else {
		    console.log('exiting current game.');
		}
		
	} else {
		res.write("You didn't mention a game.  Here's a quick list to get started.<br/>");
	}
	
	res.write('<h1>Some popular games:</h1>');
	res.write('<a href="/?game=dkong">Donkey Kong</a><br/>');
	res.write('<a href="/?game=dkongjr">Donkey Kong Jr.</a><br/>');
	res.write('<a href="/?game=mspacman">Mrs. Pac-man</a><br/>');
	res.write('<a href="/?game=galaga">Galaga</a><br/>');
	res.write('<a href="/?game=frogger">Frogger</a><br/>');
	res.write('<a href="/?game=digdug">Dig Dug</a><br/>');
	res.write('<br/><br/>');
	res.write('<a href="/?game=exit">Exit running game</a><br/>');
	
	//res.end('done.\n');
}).listen(port);
